using AutoMapper;
using B.S.ReportEvent.ApiNew.Commands.Instance;
using B.S.ReportEvent.ApiNew.Utils;
using B.S.ReportEvent.Domain.Entities;
using B.S.ReportEvent.ErrorCode;
using B.S.ReportEvent.ErrorCode.ErrorCodes;
using B.S.ReportEvent.Infrastructure.Interfaces;
using MediatR;

namespace B.S.ReportEvent.ApiNew.CommandHandlers.Instance
{
    /// <summary>
    /// 新增实例命令处理器
    /// </summary>
    public class CreateInstanceCommandHandler : IRequestHandler<CreateInstanceCommand, ApiResult>
    {
        private readonly IWfInstancesRepository _repository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateInstanceCommandHandler> _logger;
        private readonly IHttpHelper _httpHelper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="httpHelper"></param>
        public CreateInstanceCommandHandler(IWfInstancesRepository repository, IMapper mapper, ILogger<CreateInstanceCommandHandler> logger, IHttpHelper httpHelper)
        {
            _repository = repository;
            _mapper = mapper;
            _logger = logger;
            _httpHelper = httpHelper;
        }

        /// <summary>
        /// 处理新增实例命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult> Handle(CreateInstanceCommand request, CancellationToken cancellationToken)
        {
            // 参数验证 
            if (string.IsNullOrEmpty(request.FormContent))
            {
                return ApiResult.Fail("表单内容不能为空", StatusCodeEnum.Fail);
            }
            
            //验证 request.FormContent 是否是一个 Json
            
            

            try
            {
                //需要 FormType FormInfo 
                //使用 httpclient 请求另一个微服务中的数据
                var response = await _httpHelper.GetFormNodesForInstance(request.FormId);
                
                var instance = _mapper.Map<WfInstances>(request);
                instance.FormTypeNo = response.FormTypeNo;
                instance.FormTypeName = response.FormTypeName;
                instance.FormNo = response.FormNo;
                instance.FormName = response.FormName;
                instance.StarterId = response.StarterId;
                instance.StarterName = response.StarterName;
                instance.CurrentNodeNo = response.CurrentNodeNo;
                instance.CurrentNodeName = response.CurrentNodeName;
                instance.CurrentOperatorId = response.CurrentOperatorId;
                instance.CurrentOperatorName = response.CurrentOperatorName;
                instance.NextNodeNo = response.NextNodeNo;
                instance.NextNodeName = response.NextNodeName;
                instance.NextOperatorId = response.NextOperatorId;
                instance.NextOperatorName = response.NextOperatorName;
                instance.FlowStatus = 0;// 0 表示流程中  1 表示已完成
                instance.FlowStatusName = "流程中";
                instance.FormId = request.FormId;
                
                // 添加实例
                var result = await _repository.AddAsync(instance);
                
                return result == 0 ? ApiResult.Fail("添加应用实例失败", StatusCodeEnum.Fail) : ApiResult.Success(StatusCodeEnum.Ok);
                
            }
            catch (Exception e)
            {
                _logger.LogError("添加应用实例异常"+e.Message);
                return ApiResult.Fail("添加应用实例异常", StatusCodeEnum.Exception);
            }
            
            
        }
    }
}